<template>
  <div>
    <Dialog
      :title="title"
      :model-value="visible"
      width="1200px"
      max-height="900px"
      :before-close="closeForm"
    >
      <div style="width: 100%">
        <Search
          ref="search"
          :schema="scheme"
          :model="queryParam"
          :is-col="false"
          layout="inline"
          :showSearch="true"
          button-position="left"
          :search-loading="loading"
          :reset-loading="loading"
          @search="handleSearch"
          @reset="handleSearch"
        >
          <template #opts>
            <BaseButton type="success" @click="addItem">添加字典项</BaseButton>
          </template>
        </Search>
      </div>
      <Table :data="trees" :columns="columns" max-height="700px" row-key="Id" @change="load">
        <template #DicStatus="e">
          <el-switch
            v-model="e.row.DicStatus"
            :inactive-value="e.row.DicStatus == 1 ? 2 : 0"
            :active-value="1"
            @change="(value) => setStatus(e.row, value)"
          />
        </template>
        <template #Sort="e">
          <el-space>
            <BaseButton
              v-if="e.row.Sort != 1"
              :icon="topIcon"
              size="small"
              circle
              @click="upItem(e.row)"
            />
            <BaseButton
              v-if="e.row.Sort != e.row.MaxSort && e.row.MaxSort != 1"
              size="small"
              :icon="bottomIcon"
              circle
              @click="downItem(e.row, e.index)"
            />
          </el-space>
        </template>
        <template #action="e">
          <BaseButton
            size="small"
            type="warning"
            title="编辑"
            :icon="editIcon"
            circle
            @click="editItem(e.row)"
          />
          <BaseButton
            v-if="e.row.DicStatus == 0"
            size="small"
            type="danger"
            title="删除"
            :icon="dropIcon"
            circle
            @click="deleteItem(e.row)"
          />
        </template>
      </Table>
    </Dialog>
    <editTreeItem
      :id="id"
      v-model:visible="visibleEdit"
      :dic-id="dicId"
      :parent="parent"
      @close="closeEdit"
    />
  </div>
</template>

<script>
import * as dicApi from '@/api/base/treeDicItem'
import { HrEnumDic } from '@/config/publicDic'
import { Dialog } from '@/components/Dialog'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import { useIcon } from '@/hooks/web/useIcon'
import editTreeItem from './components/editTreeItem.vue'
export default {
  components: {
    Table,
    Search,
    Dialog,
    editTreeItem
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    dicName: {
      type: String,
      default: null
    },
    dicId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      topIcon: useIcon({ icon: 'ep:top' }),
      bottomIcon: useIcon({ icon: 'ep:bottom' }),
      editIcon: useIcon({ icon: 'ep:edit' }),
      dropIcon: useIcon({ icon: 'ep:delete' }),
      scheme: [
        {
          field: 'QueryKey',
          label: '关键字',
          component: 'Input',
          componentProps: {
            placeholder: '关键字'
          }
        },
        {
          field: 'Status',
          label: '字典项状态',
          component: 'EnumItem',
          componentProps: {
            dicKey: HrEnumDic.dicItemStatus,
            placeholder: '字典项状态',
            multiple: true
          }
        }
      ],
      columns: [
        {
          sortby: 'DicText',
          field: 'DicText',
          label: '字典文本',
          align: 'left',
          minWidth: 150,
          sortable: 'custom'
        },
        {
          field: 'DicValue',
          label: '字典值',
          align: 'left',
          minWidth: 200
        },
        {
          sortby: 'DicStatus',
          field: 'DicStatus',
          label: '状态',
          align: 'center',
          slotName: 'DicStatus',
          minWidth: 100,
          sortable: 'custom'
        },
        {
          sortby: 'Sort',
          field: 'Sort',
          label: '排序',
          align: 'center',
          slotName: 'Sort',
          minWidth: 100,
          sortable: 'custom'
        },
        {
          field: 'Action',
          label: '操作',
          align: 'left',
          fixed: 'right',
          width: '140px',
          slotName: 'action'
        }
      ],
      trees: [],
      parent: null,
      visibleEdit: false,
      isRefresh: false,
      id: null,
      title: '字典',
      queryParam: {
        DicId: null,
        QueryKey: null,
        Status: null
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    closeEdit(isRefresh) {
      if (isRefresh) {
        this.isRefresh = true
        this.reset()
      }
    },
    editItem(row) {
      this.id = row.Id
      this.parent = null
      this.visibleEdit = true
    },
    async reset() {
      this.title = '字典' + this.dicName + '明细'
      this.queryParam.QueryKey = null
      this.queryParam.Status = null
      this.load()
    },
    handleSearch(data) {
      this.queryParam.QueryKey = data.QueryKey
      this.queryParam.Status = data.Status
      this.load()
    },
    async upItem(row) {
      await dicApi.Move(row.Id, row.UpId)
      this.load()
    },
    async downItem(row) {
      await dicApi.Move(row.Id, row.DownId)
      this.load()
    },
    addItem(row) {
      this.id = null
      this.parent = row
      this.visibleEdit = true
    },
    deleteItem(row) {
      const title = '确认删除字典项 ' + row.DicText + '?'
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitDrop(row.Id)
      })
    },
    async setStatus(row, status) {
      if (status === 1) {
        await dicApi.Enable(row.Id)
      } else {
        await dicApi.Stop(row.Id)
      }
      row.DicStatus = status
    },
    async submitDrop(id) {
      await dicApi.DeleteItem(id)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.isRefresh = true
      this.load()
    },
    format(rows) {
      const index = rows.length - 1
      let i = 0
      rows.forEach((a) => {
        if (a.Children && a.Children.length !== 0) {
          this.format(a.Children)
        } else {
          delete a.Children
        }
        a.MaxSort = rows[index].Sort
        if (a.MaxSort !== a.Sort) {
          a.DownId = rows[i + 1].Id
        } else if (i !== 0) {
          a.UpId = rows[i - 1].Id
        }
        i = i + 1
      })
    },
    async load() {
      this.queryParam.DicId = this.dicId
      let tree = await dicApi.getTree(this.queryParam)
      if (tree == null) {
        tree = []
      }
      const index = tree.length - 1
      let i = 0
      tree.forEach((a) => {
        if (a.Children && a.Children.length !== 0) {
          this.format(a.Children)
        } else {
          delete a.Children
        }
        a.MaxSort = tree[index].Sort
        if (a.MaxSort !== a.Sort) {
          a.DownId = tree[i + 1].Id
        } else if (i !== 0) {
          a.UpId = tree[i - 1].Id
        }
        i = i + 1
      })
      console.log(tree)

      this.trees = tree
    },
    closeForm() {
      this.$emit('update:visible', false)
      this.$emit('close', this.isRefresh)
    }
  }
}
</script>
